package com.hyacinth.lotterysystem.common.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {
    private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 设置值
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, String value) {
        try {
            stringRedisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            logger.error("RedisUtil set key: {} value: {}, error: {})", key, value, e);
        }
        return false;
    }

    /**
     * 设置值 带过期时间
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, String value, Long time) {
        try {
            stringRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            logger.error("RedisUtil set key: {} value: {} time:{}, error: {} )", key, value, time, e);
        }
        return false;
    }

    /**
     * 获取值
     *
     * @param key
     * @return
     */
    public String get(String key) {
        try {
            return key == null ? null : stringRedisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            logger.error("RedisUtil error, get key: {})", key);
        }
        return null;
    }

    public boolean del(String... key) {
        try {
            if (key != null && key.length > 0) {
                if (key.length == 1) {
                    stringRedisTemplate.delete(key[0]);
                } else {
                    stringRedisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
                }
            }
            return true;
        } catch (Exception e) {
            logger.error("RedisUtil del key: {} )", key, e);
            return false;
        }
    }

    /**
     *
     * @param key
     * @return
     */
    public boolean hasKey(String key){
       try{
           return StringUtils.hasText(key) ? stringRedisTemplate.hasKey(key):false;
       }catch (Exception e){
           logger.error("RedisUtil hasKey key: {} )", key, e);
           return false;
       }
    }
}
